package fileIO;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class ReadTxtFiles {

	public String readTxtFile(String path) throws IOException {
		File file = new File(path);
		StringBuffer sb = new StringBuffer();
		try {
			String charsetName = "utf-8";

			BufferedReader br = new BufferedReader(new InputStreamReader(
					new BufferedInputStream(new FileInputStream(file)),
					charsetName));
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append(System.getProperty("line.separator"));
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			generateTxTFile(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public List<String> readTxtFileReturnLines(String path) throws IOException {
		File file = new File(path);
		List<String> lines = new LinkedList<String>();
		try {
			String charsetName = "utf-8";

			BufferedReader br = new BufferedReader(new InputStreamReader(
					new BufferedInputStream(new FileInputStream(file)),
					charsetName));
			String line;
			while ((line = br.readLine()) != null) {
				lines.add(line);
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			generateTxTFile(path);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}

	private void generateTxTFile(String path) throws IOException {
		File file = new File(path);
		file.createNewFile();
	}

}
